import {
	asyncRouterMap,
	constantRouterMap
} from '../../router/index'


import { markRaw } from 'vue'

import Layout from '../../views/Layout/Layout.vue'

/**
 * 避免浪费性能
 * 不会转为 proxy 对象，返回本身对象
 * 不是响应式对象
 * , roles: [374]
 */
const Layouts = markRaw(Layout)

/**
 * 生成路由表
 */

// 判断路由的 meta.roles 是否存在当前权限的数据里
function hasPermission(roles, router) {
	if (router.meta && router.meta.roles) {
		return roles.some(role => router.meta.roles.indexOf(role) > -1)
	} else {
		return true
	}
}

/**
 * 递归过滤 异步路由表 / asyncRouterMap，返回符合用户角色权限的路由表
 * 1. 通过 filter 递归得到 router 元素 ；
 * 2. 然后根据 roles（权限数据）进行过滤
 * 3. 判断如果 router 元素的 children 属性也还有值，那就把 router.children 再走一边 1
 */
function filterAsyncRouter(asyncRouterMap, roles) {
	const filterRouters = asyncRouterMap.filter(router => {
		if (hasPermission(roles, router)) {
			if (router.children && router.children.length) {
				router.children = filterAsyncRouter(router.children, roles)
			}
			return true
		}
		return false
	})

	return filterRouters
}

const permission = {
	state: {
		routers: constantRouterMap,
		addRouters: []
	},
	mutations: {
		SET_ROUTERS: (state, routers) => {
			state.addRouters = routers
			state.routers = constantRouterMap.concat(routers)
		}
	},
	actions: {
		// 过滤路由表
		GenerateRoutes({
			commit
		}, data) {
			return new Promise((resolve) => {
				const {
					roles
				} = data
				const filterRouters = filterAsyncRouter(asyncRouterMap, roles)
				commit('SET_ROUTERS', filterRouters)
				resolve()
			})
		},
		// 过滤路由表
		setRou({
			commit
		}, data) {
			let filterRouters = [{
				path: "",
				hidden: false,
				children: [{
					path: "",
					meta: {
						"title": "Home"
					}
				}]
			}, {
				path: "/EChartsMage",
				hidden: false,
				children: [{
					path: "",
					meta: {
						"title": "Sales"
					}
				}]
			}, {
				path: "/1",
				hidden: false,
				children: [{
					path: "",
					meta: {
						"title": "Purchases"
					}
				}]
			}, {
				path: "/2",
				hidden: false,
				children: [{
					path: "",
					meta: {
						"title": "Credit & Debit Note"
					}
				}]
			}, {
				path: "/3",
				hidden: false,
				children: [{
					path: "",
					meta: {
						"title": "Products & Services"
					}
				}]
			}, {
				path: "/4",
				hidden: false,
				children: [{
					path: "",
					meta: {
						"title": "Business Contacts"
					}
				}]
			}, {
				path: '/EChartsMage',
				component: Layouts,
				redirect: 'pieChart',
				meta: {
					title: 'ECharts 模块'
				},
				children: [{
					path: 'pieChart',
					name: 'pieChart',
					meta: {
						title: 'Cash & Bank',
						icon: 'icon-51'
					}
				}]
			}]
			commit('SET_ROUTERS', filterRouters)
		},
	}
}

export default permission
